package com.darren.framework.Exception;

import com.darren.framework.bean.ResponseBean;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.orm.hibernate5.HibernateOptimisticLockingFailureException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class GlobalControllerAdvice {


    protected Logger logger = LogManager.getLogger(getClass());

    /**
     * 业务异常
     */
    @ExceptionHandler(ArchiveException.class)
    public ResponseBean archiveException(HttpServletRequest request, ArchiveException e) {
        logger.error(e.getMessage(), e);
        return ResponseBean.isError(e.getMessage());

    }

    /**
     * Token 异常
     */
    @ExceptionHandler(TokenException.class)
    public ResponseBean tokenException(HttpServletRequest request, TokenException tokenException) {
        logger.error(tokenException.getMessage(), tokenException);
        return ResponseBean.isError(tokenException.getStatus(), tokenException.getMessage());
    }


    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseBean handleException(Exception exception) {
        logger.info(SecurityUtils.getSubject().getPrincipal());
        logger.info(exception.getMessage(), exception);
        return ResponseBean.isError("服务器错误，请联系管理员");
    }

    /**
     * Shiro 权限验证，无权限操作的异常处理
     *
     * @param request
     * @param unauthorizedException
     * @return
     */
    @ExceptionHandler(UnauthorizedException.class)
    public ResponseBean unauthorizedException(HttpServletRequest request, UnauthorizedException unauthorizedException) {
        logger.info(unauthorizedException.getMessage(), unauthorizedException);
        return ResponseBean.isWarn("您无权限操作，请联系管理人员。");

    }

    /**
     * 数据版本异常，此数据已被修改过。
     *
     * @param hibernateOptimisticLockingFailureException
     * @return
     */
    @ExceptionHandler(HibernateOptimisticLockingFailureException.class)
    public ResponseBean hibernateOptimisticLockingFailureException(HibernateOptimisticLockingFailureException hibernateOptimisticLockingFailureException) {
        logger.info(hibernateOptimisticLockingFailureException.getMessage(), hibernateOptimisticLockingFailureException);
        return ResponseBean.isWarn("数据版本低，此数据已被修改过。");
    }

}
